package study.eggs.async.mdc.task;

import org.slf4j.MDC;

import java.util.Map;
import java.util.concurrent.Callable;

public class MdcCallable<V> implements Callable<V> {

    public Callable<V> delegate;

    private final Map<String, String> contextMap;

    public MdcCallable(Callable<V> task) {
        this.delegate = task;
        this.contextMap = MDC.getCopyOfContextMap();
    }

    @Override
    public V call() throws Exception {
        V v;
        MDC.setContextMap(contextMap);
        try {
            v = delegate.call();
        } finally {
            MDC.clear();
        }
        return v;
    }
}
